package com.sky.controller.user;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.sky.constant.MessageConstant;
import com.sky.dto.OrderMessageDto;
import com.sky.dto.OrdersPaymentDTO;
import com.sky.dto.OrdersSubmitDTO;
import com.sky.entity.OrderDetail;
import com.sky.entity.Orders;
import com.sky.exception.OrderBusinessException;
import com.sky.mapper.UserMapper;
import com.sky.result.Result;
import com.sky.service.OrderService;
import com.sky.service.OrderdetailService;
import com.sky.service.Usersevice;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.websocket.WebSocketServer;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.bridge.Message;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

@RestController
@Slf4j
@RequestMapping("/user/order")
public class OrderController {
    /**
     * 用户下单
     *
     * @param ordersSubmitDTO
     * @return
     */
    @Autowired
    private Usersevice usersevice;
    @Autowired
    private WebSocketServer webSocketServer;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private OrderService orderService;
    @Autowired
    private OrderdetailService orderdetailService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @PostMapping("/submit")
    public Result ordersubmit(@RequestBody OrdersSubmitDTO ordersSubmitDTO) {
        log.info("ordersSubmitDTO is {}", ordersSubmitDTO);
        OrderSubmitVO ordersubmit = usersevice.ordersubmit(ordersSubmitDTO);
        if (ordersubmit == null) {
            return Result.error("未知错误");
        }
        //向消息队列发送消息
        //将localDatime转成毫秒值
        long time = DateUtil.toInstant(ordersubmit.getOrderTime()).toEpochMilli();
        OrderMessageDto messageDto= OrderMessageDto.builder()
                .id(String.valueOf(ordersubmit.getOrderNumber()))
                .createAt(time)
                .ttl(MessageConstant.MESSAGE_EXPIRE)
                .build();
        CorrelationData correlationData = new CorrelationData(String.valueOf(ordersubmit.getId()));
        log.info("准备发送消息到RabbitMQ: exchange={}, routingKey={}, message={}",
                MessageConstant.normalexchange, MessageConstant.normal_routinkey, messageDto);
        rabbitTemplate.convertAndSend(MessageConstant.normalexchange,MessageConstant.normal_routinkey,messageDto);
        log.info("消息发送完成，等待回调");
        return Result.success(ordersubmit);
    }

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    @PutMapping("/payment")
    @ApiOperation("订单支付")
    public Result<OrderPaymentVO> payment(@RequestBody OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        log.info("订单支付：{}", ordersPaymentDTO);
        boolean payment = orderService.payment(ordersPaymentDTO.getOrderNumber());
        if (payment == true) {
            //向redis写入已处理数据
            redisTemplate.opsForHash().put("messagestatus", ordersPaymentDTO.getOrderNumber(), 2);
        }
        return Result.success();
    }

    /**
     * 订单提醒
     *
     * @return
     * @param订单id
     */
    @GetMapping("/reminder/{id}")
    public void ordereminder(@PathVariable("id") Integer id) {
        //根据id查询订单
        Orders ordersDB = userMapper.getbyid(id);
        if (ordersDB == null) {
            throw new OrderBusinessException("订单不存在");
        }
        HashMap<Object, Object> map = new HashMap<>();
        map.put("type", 2);//type为1代表来单提醒
        map.put("orderid", id);//订单id
        map.put("content", "订单号" + ordersDB.getNumber());//订单号
        //将map转为json字符串
        String s = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(s);
    }

    @GetMapping("orderDetail/{id}")
    public Result queryorderdetail(@PathVariable("id") Integer id) {
        List<OrderDetail> queryorderdetail = orderdetailService.queryorderdetail(id);
        return Result.success(queryorderdetail);
    }

    @GetMapping("/historyOrders")
    public Result historyorder() {
        List<Orders> historybyuser = orderService.historybyuser();
        return Result.success(historybyuser);
    }
}
